-- Author: shunguo.chen
-- Date: 2016-06-17 11:42:45
--
-- FriendController
--

local FriendView = import("..views.FriendView")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ControllerBase)

--idx = 1 好友
--idx = 2 搜索玩家
--idx = 3 申请
--idx = 4 黑名单
local FRIEND_IDX = 1
local ADD_IDX = 2
local APPLY_IDX = 3
local BLACK_IDX = 4
local MSDK_IDX = 5

function ClassRef:ctor(params)
	self.super.ctor(self, params)

end

function ClassRef:init()
	self._model = app:getInst("FriendModel")

	self._curIdx = nil

	self._friendHandler = UD:onChanged("friend",function(...) self._model:updateFriends(...) end)
	self._blackHandler = UD:onChanged("black",function(...) self._model:updateBlacks(...) end)
	self._msdkDataChangeHandler = UD.msdkData:onChanged(handler(self, self._onMsdkDataChange))
end

function ClassRef:removeListeners()
	self.super.removeListeners(self)
	UD:unChanged("friend", self._friendHandler)
	UD:unChanged("black", self._blackHandler)
	UD.msdkData:unChanged(self._msdkDataChangeHandler)
end

function ClassRef:listEvent()
    return {

	}
end


function ClassRef:onEvent(eventName, data)
	if eventName == "OnGameConnected" then

	end
end

function ClassRef:openView(data)
	if cc.isDead(self._view) then
		self._view = FriendView.new(app.mvc.VIEWTYPE_BLUR)
		self._view:onCloseView(handler(self, self.closeView))
		self._view:onClearView(handler(self, self.clearView))
		self._view:onOperate(handler(self, self.onOperate))
		self._view:onSwitchPanel(handler(self, self.onSwitchPanel))
	end
	self:addChild(self._view, data)

	self._view:hide()

	-- 打开UI时 拉取最新的好友请求列表
	self._model:reqFriendRequestList()
		
	local friends = self._model:getFriends()
	if #friends > 0 then
		self._model:reqFriendsStatus(function ()
				if self._view then
					self._view:show(1)
				end
			end)
	else
		self._model:reqRecommendFriend(function()
				if self._view then
					self._view:show(2)
				end
			end)
	end

end
function ClassRef:closeView(data)
	if self._view then
		self:removeChild(self._view, data)
		self:clearView()
		tapm.markLevelFin()
	end
end
function ClassRef:clearView(data)
	if self._view then self._view = nil end
	self._model:clearRecents()
end

------------------------------ view logic ---------------------------------
function ClassRef:onOperate(operate, data)
	-- print("FriendController:onOperate = " .. operate)
	if operate == "getSearchs" then
		self:refreshFriendList(self._model:getSearchs(data))
	elseif operate == "search" then
		if app:isNeedCheckInput() then
                app:checkInput(data, function(response,errorMsg,code)
                    if code == 200 then
                        if response and response.result then
                            self._model:reqLocateUser(data)
                        else
                            display.pushToast(L("lua_code_text_11"))
                        end
                    else
                        display.pushToast(L("network_error"))
                    end
                end)
            else
                self._model:reqLocateUser(data)
            end
	elseif operate == "addFriend" then
		if type(data) == "number" then
			self._model:reqAddFriendByUID(data)
		end
	elseif operate == "removeFriend" then
		self._model:reqRemoveFriendByUID(data)
	elseif operate == "agreeAddFriend" then
		self._model:handlerFriendRequest(data.uid, data.name, true)
	elseif operate == "refruseAddFriend" then
		self._model:handlerFriendRequest(data.uid, data.name, false)
	elseif operate == "addBlack" then
		self._model:reqAddBlacklist(data)
	elseif operate == "removeBlack" then
		self._model:reqRemoveBlacklist(data)
	elseif operate == "btnMore" then
		data.type = Enums.MenuType.friend
		UIHandler:showHeadMenu(data)
	elseif operate == "btnMsdkMore" then
		UIHandler:showHeadMenu(data)
	elseif operate == "speakTo" then
		--密聊
		if data.online then
		    app:sendMsg("IMRoomController", "speakToTarget", data.info)
		else
			display.pushToast(L("tips_1050011"))
		end
	elseif operate == "team" then
		--组队
		if UIHandler:isFunctionOpen(Constant.FUNC_TYPE_CREATE_TEAM) then
			if data.online then
				if app:sendMsg("TeamModel", "isInTeam", data.uid) then
					display.pushToast(L("lua_code_text_535"))
				else
			        app:sendMsg("TeamModel", "reqInviteToTeam", data.uid, data.level)
			    end
		    else
		    	display.pushToast(L("tips_1050011"))
		    end
		else
			display.showFunctionNotOpenDetail(Constant.FUNC_TYPE_CREATE_TEAM)
	    end
	elseif operate == "detail" then
		--详情
		if data.online then
			EM:notify("onWatchUI",data.info.uid)
		else
			display.pushToast(L("tips_1050011"))
		end
	elseif operate == "applyIntoTeam" then
		--申请加入队伍
		app:sendMsg("TeamModel", "reqApplyTeamWithTargetUid", data.uid)
	end
end


--idx = 1 好友
--idx = 2 搜索玩家
--idx = 3 申请
--idx = 4 黑名单
function ClassRef:onSwitchPanel(idx, searchIdx)
	self._curIdx = idx
	local datas
	if self._curIdx == FRIEND_IDX then
		datas = self._model:getFriends()
	elseif self._curIdx == ADD_IDX then
		datas = self._model:getSearchs(searchIdx)
	elseif self._curIdx == APPLY_IDX then
		datas = self._model:getRequests()
	elseif self._curIdx == BLACK_IDX then
		datas = self._model:getBlacks()
	elseif self._curIdx == MSDK_IDX then
		datas = UD.msdkData:getMsdkFriendGameUser(true)
	end
	self:refreshFriendList(datas)
end

function ClassRef:updateFriendList(opt, friend)
	if not self:isViewAlive() then return end
	if opt == "insert" or opt == "delete" then
		if opt == "insert" then
			self._view:setNewTipVisibla(true)
		end
		if self._curIdx == FRIEND_IDX then
			self:refreshFriendList(self._model:getFriends())
		elseif self._curIdx == ADD_IDX then
			if opt == "insert" then
				self:updateSearchData(friend)
			end
		end
	elseif opt == "update" then
		if self._curIdx == FRIEND_IDX then
			local list = self._view:getFriendList()
			local items = list:getItems()
			for i,item in ipairs(items) do
				if item:getData().uid == friend.uid then
					item:setData(friend)
					break
				end
			end
		end
	end
end

function ClassRef:upadteRequestList()
	if not self:isViewAlive() then return end
	if self._curIdx ~= APPLY_IDX then return end
	self:refreshFriendList(self._model:getRequests())
end

function ClassRef:updateBlackList(opt, black)
	if not self:isViewAlive() then return end
	if opt == "insert" or opt == "delete" then
		if self._curIdx == BLACK_IDX then
			self:refreshFriendList(self._model:getBlacks())
		elseif self._curIdx == ADD_IDX then
			if opt == "insert" then
				self:updateSearchData(black)
			end
		end
	elseif opt == "update" then
		if self._curIdx == BLACK_IDX then
			local list = self._view:getFriendList()
			local items = list:getItems()
			for i,item in ipairs(items) do
				if item:getData().uid == black.uid then
					item:setData(black)
					break
				end
			end
		end
	end
end

function ClassRef:updateRecentList()
	if not self:isViewAlive() then return end
	if self._curIdx ~= ADD_IDX then return end
	self:refreshFriendList(self._model:getRecents())
end

function ClassRef:updateSearchList(users)
	if not self:isViewAlive() then return end
	if self._curIdx ~= ADD_IDX then return end
	self:refreshFriendList(users)
end

function ClassRef:updateSearchData(user)
	if not self:isViewAlive() then return end
	local listView = self._view:getFriendList()
	local items = listView:getItems()
	for i, item in ipairs(items) do
		if item:getData() and item:getData().uid == user.uid then
			listView:removeItem(i-1)
			break
		end
	end
end

function ClassRef:notifyAddFriend(data)
	local confirmDialog = display.newConfirmDialog( string.format( L("lua_code_text_127"), data.name), 
		function()
			self._model:handlerFriendRequest(data.uid, data.name, true)
		end)
	UIHandler:addPopDialog(confirmDialog)
end

-----------------------------------------------------------------------
function ClassRef:refreshFriendList(datas)
	local listView = self._view:getFriendList()
	listView:stopAllActions()

	local len = #datas
	self._view:refreshNum(len)
	
	self._view:cleanListView()
	local curIdx = 0
	local function addFriend()
		curIdx = curIdx + 1
		if curIdx <= len then
			local render = listView:createRender(curIdx)
			render:setData(datas[curIdx])
			render:onBtnClick(handler(self, self.onOperate))
		else
			--删掉多余的item
			display.removeListUnuseItem(listView, len)
			listView:stopAllActions()
		end
	end

	if len > 0 then
		local items = listView:getItems()
		for i,item in ipairs(items) do
			item:setVisible(false)
		end
		listView:setVisible(true)
		listView:schedule(addFriend, 0)
	else
		listView:setVisible(false)
	end
end


function ClassRef:_onMsdkDataChange()
	if not self:isViewAlive() then return end

    if self._curIdx == MSDK_IDX then
		local datas = UD.msdkData:getMsdkFriendGameUser()
		self:refreshFriendList(datas)
	end
	
end


return ClassRef
